package com.study.easyexcel.business.template;

import com.alibaba.excel.util.ListUtils;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Workbook;

import java.text.MessageFormat;
import java.util.List;

/**
 * 直填属性的样式处理器，非列表填充统一的样式处理器
 *
 * @author yuhuan
 * @date 2024/1/5
 */
public class DefaultMetaStyle extends UniversalGroupStyle {

    private List<Integer> totalRowIndex;

    @Override
    protected void setCellFormula(CellWriteHandlerContext context, Cell cell) {
        Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
        int columnIndex = cell.getColumnIndex();
        DataFormat format = workbook.createDataFormat();
        CellStyle cellStyle = cell.getCellStyle();
        if (cellStyle == null) {
            cellStyle = workbook.createCellStyle();
        }
        String fx = "未知开发";
        if (columnIndex == 1 || columnIndex == 5 || columnIndex == 9 || columnIndex == 13) {
            fx = MessageFormat.format("IFERROR({0},\"\")", String.join("+", countSplicing(getColumnChar(columnIndex))));
        } else if (columnIndex == 3 || columnIndex == 7 || columnIndex == 11 || columnIndex == 15) {
            cellStyle.setDataFormat(format.getFormat("0.00"));
            fx = MessageFormat.format("IFERROR({0},\"\")", String.join("+", countSplicing(getColumnChar(columnIndex))));
        }
        cell.setCellFormula(fx);
    }

    public void setTotalRowIndex(List<Integer> totalRowIndex) {
        totalRowIndex.sort(Integer::compareTo);
        this.totalRowIndex = totalRowIndex;
    }

    public List<Integer> getTotalRowIndex() {
        return totalRowIndex;
    }

    /**
     * 获取当前列所有合计行的单元格信息。如：B1,B4,B5
     */
    private List<String> countSplicing(String columnChar) {
        List<String> rowList = ListUtils.newArrayList();
        for (Integer rowIndex : this.totalRowIndex) {
            int rowNum = rowIndex + 1;
            rowList.add(columnChar + rowNum);
        }
        return rowList;
    }

    /**
     * 获取列索引对应的单元格字母
     */
    private String getColumnChar(Integer columnIndex) {
        switch (columnIndex) {
            case 1:
                return "B";
            case 3:
                return "D";
            case 5:
                return "F";
            case 7:
                return "H";
            case 9:
                return "J";
            case 11:
                return "L";
            case 13:
                return "N";
            case 15:
                return "P";
            default:
                return "";
        }
    }
}
